// 1. React核心库
import React, { useEffect, useState } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, Card, Form, Input, InputNumber, Space, message } from 'antd';

// 3. 图标库
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer } from '@ant-design/pro-components';

// 5. 路由和状态管理
import { useParams } from '@umijs/max';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { PermissionCategory } from '@/services/generated';

const { TextArea } = Input;

const PermissionCategoryForm: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [initialLoading, setInitialLoading] = useState(false);
  const params = useParams<{ id?: string }>();

  const isEdit = !!params.id;
  const title = isEdit ? '编辑权限分类' : '新建权限分类';

  // 加载数据（编辑模式）
  useEffect(() => {
    if (isEdit && params.id) {
      loadData(parseInt(params.id));
    }
  }, [isEdit, params.id]);

  const loadData = async (id: number) => {
    setInitialLoading(true);
    try {
      await autoLoginInDev();
      const response = await apiClients.permissions.permissionsCategoriesRetrieve({ id });
      form.setFieldsValue(response.data);
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setInitialLoading(false);
    }
  };

  // 提交表单
  const handleSubmit = async (values: Partial<PermissionCategory>) => {
    setLoading(true);
    try {
      await autoLoginInDev();
      if (isEdit && params.id) {
        // 更新
        await apiClients.permissions.permissionsCategoriesUpdate({
          id: parseInt(params.id),
          permissionCategoryRequest: values as any,
        });
        message.success('更新权限分类成功');
      } else {
        // 创建
        await apiClients.permissions.permissionsCategoriesCreate({
          permissionCategoryRequest: values as any,
        });
        message.success('创建权限分类成功');
      }

      // 返回列表页
      window.location.href = '/permissions/categories';
    } catch (error) {
      message.error('保存失败');
    } finally {
      setLoading(false);
    }
  };

  // 返回列表
  const handleBack = () => {
    window.location.href = '/permissions/categories';
  };

  return (
    <PageContainer title={title} loading={initialLoading}>
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            sort_order: 0,
          }}
        >
          <Form.Item
            label="分类名称"
            name="name"
            rules={[
              { required: true, message: '请输入分类名称' },
              { max: 50, message: '分类名称不能超过50个字符' },
            ]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>

          <Form.Item
            label="分类代码"
            name="code"
            rules={[
              { required: true, message: '请输入分类代码' },
              { max: 50, message: '分类代码不能超过50个字符' },
              { pattern: /^[a-z_]+$/, message: '分类代码只能包含小写字母和下划线' },
            ]}
          >
            <Input placeholder="请输入分类代码，如：user_management" />
          </Form.Item>

          <Form.Item
            label="描述"
            name="description"
            rules={[
              { max: 500, message: '描述不能超过500个字符' },
            ]}
          >
            <TextArea
              rows={4}
              placeholder="请输入分类描述"
            />
          </Form.Item>

          <Form.Item
            label="排序"
            name="sort_order"
            rules={[
              { type: 'number', min: 0, message: '排序值不能小于0' },
            ]}
          >
            <InputNumber
              min={0}
              max={999}
              placeholder="请输入排序值"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                icon={<SaveOutlined />}
              >
                {isEdit ? '更新' : '创建'}
              </Button>
              <Button onClick={handleBack}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default PermissionCategoryForm;
